import React, {useRef, useState} from "react";
import {
    Avatar,
    Button,
    Card,
    Input,
    type InputRef,
    Space,
    Table, TableColumnsType,
    type TableColumnType,
    Tag
} from "antd";
import useAdminInformation from "@/hooks/get_admin_information.ts";
import {adminInfo} from "@/vite-env";
import type {FilterDropdownProps} from "antd/es/table/interface";
import {SearchOutlined} from "@ant-design/icons";
import Highlighter from "react-highlight-words";

type DataIndex = keyof adminInfo;

const Admin_Information: React.FC = () => {
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const searchInput = useRef<InputRef>(null);

    const handleSearch = (
        selectedKeys: string[],
        confirm: FilterDropdownProps['confirm'],
        dataIndex: DataIndex,
    ) => {
        confirm();
        setSearchText(selectedKeys[0]);
        setSearchedColumn(dataIndex);
    };

    const handleReset = (clearFilters: () => void) => {
        clearFilters();
        setSearchText('');
    };

    const getColumnSearchProps = (dataIndex: DataIndex): TableColumnType<adminInfo> => ({
        filterDropdown: ({setSelectedKeys, selectedKeys, confirm, clearFilters}) => (
            <div style={{padding: 8}} onKeyDown={(e) => e.stopPropagation()}>
                <Input
                    ref={searchInput}
                    placeholder={`Search ${dataIndex}`}
                    value={selectedKeys[0]}
                    onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                    onPressEnter={() => handleSearch(selectedKeys as string[], confirm, dataIndex)}
                    style={{marginBottom: 8, display: 'block'}}
                />
                <Space>
                    <Button
                        type="primary"
                        onClick={() => handleSearch(selectedKeys as string[], confirm, dataIndex)}
                        icon={<SearchOutlined/>}
                        size="small"
                        style={{width: 90}}
                    >
                        查询
                    </Button>
                    <Button
                        onClick={() => clearFilters && handleReset(clearFilters)}
                        size="small"
                        style={{width: 90}}
                    >
                        重置
                    </Button>
                </Space>
            </div>
        ),
        filterIcon: (filtered: boolean) => (
            <SearchOutlined style={{color: filtered ? '#1677ff' : undefined}}/>
        ),
        onFilter: (value, record) =>
            (record as { [key: string]: any })[dataIndex]
                .toString()
                .toLowerCase()
                .includes((value as string).toLowerCase()),
        onFilterDropdownOpenChange: (visible) => {
            if (visible) {
                setTimeout(() => searchInput.current?.select(), 100);
            }
        },
        render: (text) =>
            searchedColumn === dataIndex ? (
                <Highlighter
                    highlightStyle={{backgroundColor: '#ffc069', padding: 0}}
                    searchWords={[searchText]}
                    autoEscape
                    textToHighlight={text ? text.toString() : ''}
                />
            ) : (
                text
            ),
    });
    const columns: TableColumnsType<adminInfo> = [
        {
            title: '管理员ID',
            dataIndex: 'id',
            key: 'id',
            render: (text: number) => <b>{text}</b>,
            width: 100,
            align: 'center'
        },
        {
            title: '管理员昵称',
            dataIndex: 'username',
            ellipsis: true,
            key: 'username',
            render: (text: string) => <b>{text}</b>,
            align: 'center',
            ...getColumnSearchProps('username')

        },
        {
            title: '管理员头像',
            dataIndex: 'avatarURL',
            key: 'avatarURL',
            align: 'center',
            render: (text: string | number | boolean | React.ReactElement<any, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | React.ReactPortal | null | undefined) =>
                <Avatar size={60} src={text} shape={"square"}/>

        },
        {
            title: '管理员权限',
            dataIndex: 'authority',
            key: 'authority',
            align: 'center',
            render: (text: number) => <Tag
                color={text === 0 ? 'green' : 'blue'}>{text === 0 ? '超级管理员' : '管理员'}</Tag>,
            filters: [
                {text: '超级管理员', value: '1'},
                {text: '管理员', value: '0'},
            ],
            onFilter: (value, record) => String(record.authority) === value,
        },
        {
            title: '管理员地址',
            dataIndex: 'address',
            key: 'address',
            ellipsis: true,
            align: 'center',
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            key: 'email',
            align: 'center',
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            render: () => (
                <Space size="middle">
                    <Button type="primary">详情</Button>
                    <Button type="primary" danger>删除</Button>
                </Space>
            ),
        },
    ];
    // 获取管理员信息
    const {admin_information} = useAdminInformation()
    return (
        <Card
            bordered={false}
            style={{width: '100%', height: '90vh'}}
        >
            <Table sticky={true} columns={columns} dataSource={admin_information} scroll={{y: 530}}
                   pagination={{
                       pageSize: 20,
                   }}/>
        </Card>
    )
}

export default Admin_Information